package cc.aliza.lib.mongo.core.utils;

import cc.aliza.lib.mongo.core.AlizaEntity;
import com.mongodb.DBRef;
import org.bson.types.ObjectId;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
public final class ReferenceUtil {

    public static DBRef toDBRef(AlizaEntity entity) {
        return toDBRef(entity.getClass(), entity.getId());
    }

    public static DBRef toDBRef(Class<?> clazz, String id) {
        if (StringUtil.isEmpty(id)) {
            return null;
        }
        return new DBRef(MapperUtil.getDBName(clazz), new ObjectId(id));
    }

    public static String fromDBRef(Object value) {
        DBRef dbRef = (DBRef) value;
        return dbRef.getId().toString();
    }
}
